package com.doubao.device.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.doubao.common.result.Result;
import com.doubao.device.config.ResultHandlerUtils;
import com.doubao.device.dto.AIModelInfoDTO;
import com.doubao.device.dto.SmartDeviceDTO;
import com.doubao.device.dto.request.CreateDeviceRequest;
import com.doubao.device.dto.request.DeviceQueryRequest;
import com.doubao.device.dto.request.UpdateDeviceRequest;
import com.doubao.device.entity.SmartDevice;
import com.doubao.device.service.DeviceVoiceService;
import com.doubao.device.service.SmartDeviceService;
import com.doubao.user.entity.MembershipOperationLog;
import com.doubao.user.mapper.MembershipOperationLogMapper;
import com.doubao.user.service.MembershipService;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/device")
@RequiredArgsConstructor
@Slf4j
@Tag(name = "智能体管理", description = "智能体相关接口")
public class SmartDeviceController {

    private final SmartDeviceService deviceService;
    private final DeviceVoiceService voiceService;
    private final ObjectMapper objectMapper;
    private final ResultHandlerUtils resultHandler;
    private final MembershipService membershipService;
    private final MembershipOperationLogMapper operationLogMapper;

    /**
     * 创建智能体
     */
    @PostMapping
    @Operation(summary = "创建智能体", description = "创建一个新的智能体")
    public Result<SmartDeviceDTO> createDevice(
            @Parameter(description = "用户ID") @RequestHeader(value = "X-User-ID", required = false) Long userId,
            @Validated @RequestBody CreateDeviceRequest request) {
        return deviceService.createDevice(userId, request);
    }

    /**
     * 更新智能体
     */
    @PutMapping
    @Operation(summary = "更新智能体", description = "更新智能体信息")
    public Result<SmartDeviceDTO> updateDevice(
            @Parameter(description = "用户ID") @RequestHeader(value = "X-User-ID", required = false) Long userId,
            @Validated @RequestBody UpdateDeviceRequest request) {
        return deviceService.updateDevice(userId, request);
    }

    /**
     * 删除智能体
     */
    @DeleteMapping("/{deviceId}")
    @Operation(summary = "删除智能体", description = "删除指定的智能体")
    public Result<Void> deleteDevice(
            @Parameter(description = "用户ID") @RequestHeader(value = "X-User-ID", required = false) Long userId,
            @Parameter(description = "智能体ID") @PathVariable Long deviceId) {
        return deviceService.deleteDevice(userId, deviceId);
    }

    /**
     * 获取智能体详情
     */
    @GetMapping("/{deviceId}")
    @Operation(summary = "获取智能体详情", description = "获取指定智能体的详细信息")
    public Result<SmartDeviceDTO> getDeviceDetail(
            @Parameter(description = "用户ID") @RequestHeader(value = "X-User-ID", required = false) Long userId,
            @Parameter(description = "智能体ID") @PathVariable Long deviceId) {
        return deviceService.getDeviceDetail(deviceId, userId);
    }

    /**
     * 分页查询智能体
     */
    @GetMapping("/list")
    @Operation(summary = "分页查询智能体", description = "根据条件分页查询智能体列表")
    public Result<IPage<SmartDeviceDTO>> pageDevices(
            @Parameter(description = "用户ID") @RequestHeader(value = "X-User-ID", required = false) Long userId,
            @Validated DeviceQueryRequest request) {
        try {
            // 调用服务
            Object result = deviceService.pageDevices(request, userId);

            // 使用结果处理工具处理返回结果
            return resultHandler.handlePageResult(result, IPage.class, SmartDeviceDTO.class);
        } catch (Exception e) {
            log.error("分页查询智能体异常", e);
            return Result.failed("查询失败: " + e.getMessage());
        }
    }

    /**
     * 获取推荐智能体
     */
    @GetMapping("/recommend")
    @Operation(summary = "获取推荐智能体", description = "获取推荐的智能体列表")
    public Result<List<SmartDeviceDTO>> getRecommendDevices(
            @Parameter(description = "用户ID") @RequestHeader(value = "X-User-ID", required = false) Long userId,
            @Parameter(description = "数量限制") @RequestParam(defaultValue = "10") Integer limit) {
        try {
            Object result = deviceService.getRecommendDevices(limit, userId);
            return resultHandler.handleListResult(result, SmartDeviceDTO.class);
        } catch (Exception e) {
            log.error("获取推荐智能体异常", e);
            return Result.failed("查询失败: " + e.getMessage());
        }
    }

    /**
     * 获取热门智能体
     */
    @GetMapping("/hot")
    @Operation(summary = "获取热门智能体", description = "获取热门的智能体列表")
    public Result<List<SmartDeviceDTO>> getHotDevices(
            @Parameter(description = "用户ID") @RequestHeader(value = "X-User-ID", required = false) Long userId,
            @Parameter(description = "数量限制") @RequestParam(defaultValue = "10") Integer limit) {
        try {
            Object result = deviceService.getHotDevices(limit, userId);
            return resultHandler.handleListResult(result, SmartDeviceDTO.class);
        } catch (Exception e) {
            log.error("获取热门智能体异常", e);
            return Result.failed("查询失败: " + e.getMessage());
        }
    }

    /**
     * 获取最新智能体
     */
    @GetMapping("/latest")
    @Operation(summary = "获取最新智能体", description = "获取最新的智能体列表")
    public Result<List<SmartDeviceDTO>> getLatestDevices(
            @Parameter(description = "用户ID") @RequestHeader(value = "X-User-ID", required = false) Long userId,
            @Parameter(description = "数量限制") @RequestParam(defaultValue = "10") Integer limit) {
        try {
            Object result = deviceService.getLatestDevices(limit, userId);
            return resultHandler.handleListResult(result, SmartDeviceDTO.class);
        } catch (Exception e) {
            log.error("获取最新智能体异常", e);
            return Result.failed("查询失败: " + e.getMessage());
        }
    }

    /**
     * 获取用户创建的智能体
     */
    @GetMapping("/user")
    @Operation(summary = "获取用户创建的智能体", description = "获取指定用户创建的智能体列表")
    public Result<IPage<SmartDeviceDTO>> getUserDevices(
            @Parameter(description = "用户ID") @RequestHeader(value = "X-User-ID", required = false) Long userId,
            @Parameter(description = "页码") @RequestParam(defaultValue = "1") Integer page,
            @Parameter(description = "每页大小") @RequestParam(defaultValue = "10") Integer size) {
        try {
            Object result = deviceService.getUserDevices(userId, page, size);
            return resultHandler.handlePageResult(result, IPage.class, SmartDeviceDTO.class);
        } catch (Exception e) {
            log.error("获取用户创建智能体异常", e);
            return Result.failed("查询失败: " + e.getMessage());
        }
    }

    /**
     * 搜索智能体
     */
    @GetMapping("/search")
    @Operation(summary = "搜索智能体", description = "根据关键词搜索智能体")
    public Result<IPage<SmartDeviceDTO>> searchDevices(
            @Parameter(description = "用户ID") @RequestHeader(value = "X-User-ID", required = false) Long userId,
            @Parameter(description = "关键词") @RequestParam String keyword,
            @Parameter(description = "页码") @RequestParam(defaultValue = "1") Integer page,
            @Parameter(description = "每页大小") @RequestParam(defaultValue = "10") Integer size) {
        try {
            Object result = deviceService.searchDevices(keyword, page, size, userId);
            return resultHandler.handlePageResult(result, IPage.class, SmartDeviceDTO.class);
        } catch (Exception e) {
            log.error("搜索智能体异常", e);
            return Result.failed("查询失败: " + e.getMessage());
        }
    }

    /**
     * 更新智能体状态
     */
    @PutMapping("/{deviceId}/status")
    @Operation(summary = "更新智能体状态", description = "更新指定智能体的状态")
    public Result<Void> updateStatus(
            @Parameter(description = "用户ID") @RequestHeader(value = "X-User-ID", required = false) Long userId,
            @Parameter(description = "智能体ID") @PathVariable Long deviceId,
            @Parameter(description = "状态 1:正常 0:禁用") @RequestParam Integer status) {
        return deviceService.updateStatus(userId, deviceId, status);
    }

    /**
     * 增加智能体使用次数
     */
    @PostMapping("/{deviceId}/usage")
    @Operation(summary = "增加智能体使用次数", description = "增加指定智能体的使用次数")
    public Result<Void> increaseUsageCount(
            @Parameter(description = "智能体ID") @PathVariable Long deviceId) {
        return deviceService.increaseUsageCount(deviceId);
    }

    /**
     * 增加智能体token使用量
     */
    @PostMapping("/{deviceId}/token-usage")
    @Operation(summary = "增加智能体token使用量", description = "增加指定智能体的token使用量")
    public Result<Void> increaseTokenUsage(
            @Parameter(description = "智能体ID") @PathVariable Long deviceId,
            @Parameter(description = "输入tokens") @RequestParam Long promptTokens,
            @Parameter(description = "输出tokens") @RequestParam Long completionTokens) {
        return deviceService.increaseTokenUsage(deviceId, promptTokens, completionTokens);
    }

    /**
     * 获取智能体绑定的AI模型信息
     */
    @GetMapping("/{deviceId}/ai-model")
    @Operation(summary = "获取智能体绑定的AI模型信息", description = "获取指定智能体绑定的AI模型信息")
    public Result<AIModelInfoDTO> getDeviceAIModel(
            @Parameter(description = "智能体ID") @PathVariable Long deviceId) {
        try {
            Object result = deviceService.getDeviceAIModel(deviceId);
            return resultHandler.handleServiceResult(result, AIModelInfoDTO.class);
        } catch (Exception e) {
            log.error("获取AI模型信息异常", e);
            return Result.failed("查询失败: " + e.getMessage());
        }
    }

    /**
     * 获取智能体配置信息（包括API和语音配置）
     */
    @GetMapping("/{deviceId}/config")
    @Operation(summary = "获取智能体配置信息", description = "获取指定智能体的完整配置信息，包括API和语音配置")
    public Result<SmartDeviceDTO> getDeviceConfig(
            @Parameter(description = "智能体ID") @PathVariable Long deviceId,
            @Parameter(description = "用户ID") @RequestHeader(value = "X-User-ID", required = false) Long userId) {
        try {
            Object result = deviceService.getDeviceConfig(deviceId, userId);
            return resultHandler.handleServiceResult(result, SmartDeviceDTO.class);
        } catch (Exception e) {
            log.error("获取设备配置异常", e);
            return Result.failed("查询失败: " + e.getMessage());
        }
    }

    /**
     * 根据分类获取智能体
     */
    @GetMapping("/list/category/{categoryId}")
    @Operation(summary = "根据分类获取智能体", description = "获取指定分类下的智能体列表")
    public Result<IPage<SmartDeviceDTO>> getDevicesByCategory(
            @Parameter(description = "用户ID") @RequestHeader(value = "X-User-ID", required = false) Long userId,
            @Parameter(description = "分类ID") @PathVariable Long categoryId,
            @Parameter(description = "页码") @RequestParam(defaultValue = "1") Integer page,
            @Parameter(description = "每页大小") @RequestParam(defaultValue = "10") Integer size) {
        try {
            // 调用服务
            Object result = deviceService.getDevicesByCategory(categoryId, page, size, userId);

            // 使用结果处理工具处理返回结果
            return resultHandler.handlePageResult(result, IPage.class, SmartDeviceDTO.class);
        } catch (Exception e) {
            log.error("获取分类智能体异常", e);
            return Result.failed("查询失败: " + e.getMessage());
        }
    }

    /**
     * 根据标签获取智能体
     */
    @GetMapping("/list/tag/{tagId}")
    @Operation(summary = "根据标签获取智能体", description = "获取指定标签下的智能体列表")
    public Result<IPage<SmartDeviceDTO>> getDevicesByTag(
            @Parameter(description = "用户ID") @RequestHeader(value = "X-User-ID", required = false) Long userId,
            @Parameter(description = "标签ID") @PathVariable Long tagId,
            @Parameter(description = "页码") @RequestParam(defaultValue = "1") Integer page,
            @Parameter(description = "每页大小") @RequestParam(defaultValue = "10") Integer size) {
        try {
            // 调用服务
            Object result = deviceService.getDevicesByTag(tagId, page, size, userId);

            // 使用结果处理工具处理返回结果
            return resultHandler.handlePageResult(result, IPage.class, SmartDeviceDTO.class);
        } catch (Exception e) {
            log.error("获取标签智能体异常", e);
            return Result.failed("查询失败: " + e.getMessage());
        }
    }

    /**
     * 获取公共智能体列表
     */
    /**
     * 获取公共智能体列表 - 简化版
     */
    @GetMapping("/public")
    @Operation(summary = "获取公共智能体列表", description = "获取公共的智能体列表")
    public Result<IPage<SmartDeviceDTO>> getPublicDevices(
            @Parameter(description = "用户ID") @RequestHeader(value = "X-User-ID", required = false) Long userId,
            @Parameter(description = "页码") @RequestParam(defaultValue = "1") Integer current,
            @Parameter(description = "每页大小") @RequestParam(defaultValue = "10") Integer size,
            @Parameter(description = "分类") @RequestParam(required = false) String category) {

        try {
            // 直接通过MyBatis-Plus基本查询获取数据
            Page<SmartDevice> page = new Page<>(current, size);
            LambdaQueryWrapper<SmartDevice> queryWrapper = new LambdaQueryWrapper<>();

            queryWrapper.eq(SmartDevice::getIsPublic, 1)
                    .eq(SmartDevice::getDeleted, 0)
                    .eq(SmartDevice::getStatus, 1);

            // 添加分类条件
            if (StringUtils.isNotBlank(category)) {
                try {
                    Long categoryId = Long.parseLong(category);
                    queryWrapper.eq(SmartDevice::getCategoryId, categoryId);
                } catch (NumberFormatException e) {
                    log.warn("无效的分类ID格式: {}", category);
                }
            }

            // 排序
            queryWrapper.orderByDesc(SmartDevice::getUpdatedAt);

            // 执行查询
            IPage<SmartDevice> result = deviceService.page(page, queryWrapper);

            // 创建返回DTO页面对象
            IPage<SmartDeviceDTO> dtoPage = new Page<>(result.getCurrent(), result.getSize(), result.getTotal());
            List<SmartDeviceDTO> records = new ArrayList<>();

            // 简单转换，不调用可能不存在的方法
            for (SmartDevice device : result.getRecords()) {
                SmartDeviceDTO dto = new SmartDeviceDTO();
                BeanUtils.copyProperties(device, dto);

                // 使用服务层方法获取正确的用户昵称
                dto.setCreatorName(deviceService.getUserDisplayName(device.getUserId()));

                // 跳过可能有问题的收藏状态检查
                dto.setCollected(false);

                // 处理能力列表
                if (StringUtils.isNotBlank(device.getAbilities())) {
                    dto.setAbilities(Arrays.asList(device.getAbilities().split(",")));
                } else {
                    dto.setAbilities(new ArrayList<>());
                }

                records.add(dto);
            }

            dtoPage.setRecords(records);
            return Result.success(dtoPage);

        } catch (Exception e) {
            log.error("获取公共智能体异常", e);
            return Result.failed("查询失败: " + e.getMessage());
        }
    }

    /**
     * 获取私有智能体列表
     */
    @GetMapping("/private")
    @Operation(summary = "获取私有智能体列表", description = "获取当前用户的私有智能体列表")
    public Result<IPage<SmartDeviceDTO>> getPrivateDevices(
            @Parameter(description = "用户ID") @RequestHeader(value = "X-User-ID", required = false) Long userId,
            @Parameter(description = "页码") @RequestParam(defaultValue = "1") Integer current,
            @Parameter(description = "每页大小") @RequestParam(defaultValue = "10") Integer size) {

        try {
            // 直接通过MyBatis-Plus基本查询获取数据
            Page<SmartDevice> page = new Page<>(current, size);
            LambdaQueryWrapper<SmartDevice> queryWrapper = new LambdaQueryWrapper<>();

            // 设置基本查询条件 - 私有设备
            queryWrapper.eq(SmartDevice::getUserId, userId)
                    .eq(SmartDevice::getIsPublic, 0)
                    .eq(SmartDevice::getDeleted, 0)
                    .eq(SmartDevice::getStatus, 1);

            // 排序 - 按更新时间倒序
            queryWrapper.orderByDesc(SmartDevice::getUpdatedAt);

            // 执行查询
            IPage<SmartDevice> result = deviceService.page(page, queryWrapper);

            // 创建返回DTO页面对象
            IPage<SmartDeviceDTO> dtoPage = new Page<>(result.getCurrent(), result.getSize(), result.getTotal());
            List<SmartDeviceDTO> records = new ArrayList<>();

            // 简单转换
            for (SmartDevice device : result.getRecords()) {
                SmartDeviceDTO dto = new SmartDeviceDTO();
                BeanUtils.copyProperties(device, dto);

                // 使用服务层方法获取正确的用户昵称
                dto.setCreatorName(deviceService.getUserDisplayName(device.getUserId()));

                // 已经是当前用户的设备，所以不需要检查收藏状态
                dto.setCollected(false);

                // 处理能力列表
                if (StringUtils.isNotBlank(device.getAbilities())) {
                    dto.setAbilities(Arrays.asList(device.getAbilities().split(",")));
                } else {
                    dto.setAbilities(new ArrayList<>());
                }

                // 处理知识库ID列表
                if (StringUtils.isNotBlank(device.getKnowledgeBaseIds())) {
                    try {
                        dto.setKnowledgeBaseIds(Arrays.stream(device.getKnowledgeBaseIds().split(","))
                                .map(Long::parseLong)
                                .collect(Collectors.toList()));
                    } catch (Exception e) {
                        log.warn("解析知识库ID列表失败: {}", device.getKnowledgeBaseIds());
                        dto.setKnowledgeBaseIds(new ArrayList<>());
                    }
                } else {
                    dto.setKnowledgeBaseIds(new ArrayList<>());
                }

                records.add(dto);
            }

            dtoPage.setRecords(records);
            return Result.success(dtoPage);

        } catch (Exception e) {
            log.error("获取私有智能体异常", e);
            return Result.failed("查询失败: " + e.getMessage());
        }
    }

    /**
     * 切换智能体
     */
    @PostMapping("/switch")
    @Operation(summary = "切换智能体", description = "切换到指定智能体")
    public Result<Void> switchDevice(
            @Parameter(description = "用户ID") @RequestHeader(value = "X-User-ID", required = false) Long userId,
            @Parameter(description = "智能体ID") @RequestParam Long deviceId) {
        if (userId == null) {
            return Result.failed("用户未登录");
        }

        // 查询智能体信息
        SmartDevice device = deviceService.getById(deviceId);
        if (device == null) {
            return Result.failed("智能体不存在");
        }

        // 检查智能体是否为会员专属
        if (device.getIsPremium() == 1) {
            // 如果是会员智能体，检查用户是否是会员
            Result<Void> membershipResult = membershipService.consumeSwitchCount(userId);
            if (!membershipResult.isSuccess()) {
                return membershipResult; // 如果不是会员，返回错误信息
            }
        }

        // 增加使用次数
        deviceService.increaseUsageCount(deviceId);

        // 记录智能体切换操作
        MembershipOperationLog log = new MembershipOperationLog();
        log.setUserId(userId);
        log.setOperationType("SWITCH_AGENT");
        log.setDescription("切换智能体: " + device.getName());
        log.setNewValue("deviceId:" + deviceId);
        log.setCreatedAt(LocalDateTime.now());
        operationLogMapper.insert(log);

        return Result.success();
    }
}
